package com.qo.qsdk.event;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Dispatcher implements IDispatcher {

    private WeakReference<Object> mTarget;
    private Method mMethod;
    private boolean mIsStatic;
    private boolean mHasArgs;

    Dispatcher(Object target, Method method) {

        mTarget = new WeakReference<>(target);
        mMethod = method;
        mMethod.setAccessible(true);

        boolean has_args = false;
        Class<?>[] parameterTypes = mMethod.getParameterTypes();
        if (!(parameterTypes == null || parameterTypes.length == 0)) {
            has_args = true;
        }

        mIsStatic = Modifier.isStatic(mMethod.getModifiers());

        mHasArgs = has_args;
    }

    @Override
    public boolean dispatch(Object... args) {
        try {
            if (mIsStatic) {
                if (mHasArgs) {
                    mMethod.invoke(null, args);
                } else {
                    mMethod.invoke(null);
                }
                return true;
            } else if (mTarget.get() == null) {
                return false;
            } else {
                if (mHasArgs) {
                    mMethod.invoke(mTarget.get(), args);
                } else {
                    mMethod.invoke(mTarget.get());
                }
                return true;
            }
        } catch (IllegalAccessException e) {
            return false;
        } catch (IllegalArgumentException e) {
            return false;
        } catch (InvocationTargetException e) {
            return false;
        }
    }
}
